package com.ljx.recruitment.oss.service.strategy;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.ljx.recruitment.common.exception.ApiException;
import com.ljx.recruitment.oss.config.ALiYunConfig;
import com.ljx.recruitment.oss.domain.dto.FileDto;
import com.ljx.recruitment.oss.domain.entity.FileEntity;
import com.ljx.recruitment.oss.service.OssStrategy;
import com.ljx.recruitment.oss.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-12-14  21:04
 */
@Slf4j
@Service
public class ALiYunStrategy implements OssStrategy {

    @Autowired
    private ALiYunConfig aliYunConfig;

    @Override
    public void saveFile(FileDto file) {
        String bucketName = aliYunConfig.getBucketName();
        String filename = file.getFilename();
        String extension = FileUtil.getFileExtension(filename);
        String filePath = getFilePath(extension, file.getFileMd5());
        file.setFilePath(filePath);
        OSS ossClient = getOssClient();
        try {
            ossClient.putObject(bucketName, filePath, file.getMultipartFile().getInputStream());
        } catch (IOException e) {
            log.error("上传文件出错:{}", e.getMessage());
            throw new ApiException("上传文件出错");
        } finally {
            ossClient.shutdown();
        }
    }

    @Override
    public byte[] getFile(FileEntity fileEntity) {
        OSS ossClient = getOssClient();
        OSSObject ossObject = ossClient.getObject(aliYunConfig.getBucketName(), fileEntity.getFilePath());
        try {
            return IOUtils.toByteArray(ossObject.getObjectContent());
        } catch (IOException e) {
            log.error("下载文件出错:{}", e.getMessage());
            throw new ApiException("下载文件出错");
        }
    }

    @Override
    public void deleteFile(FileEntity fileEntity) {
        OSS ossClient = getOssClient();
        ossClient.deleteObject(aliYunConfig.getBucketName(), fileEntity.getFilePath());
    }

    private OSS getOssClient(){
        String endPoint = aliYunConfig.getEndPoint();
        String accessKeyId = aliYunConfig.getAccessKeyId();
        String accessKeySecret = aliYunConfig.getAccessKeySecret();

        return new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
    }

    private String getFilePath(String extension, String fileMd5){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String absolutePath = sdf.format(new Date()).replace("-", "/");
        return absolutePath + '/' + fileMd5 + "." + extension;
    }
}
